package a66weding.com.jiehuntong.activity.imageupload.activity.takephoto;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.FileOutputStream;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.imageupload.activity.AlbumActivity;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.Bimp;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.ImageItem;
import a66weding.com.jiehuntong.activity.order.ApplyServiceOneActivity;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;

/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/9/23
 * @description :
 */
public class SelectPicPopupWindow  extends Activity implements View.OnClickListener {

    private Intent intent;

    private Button btn_take_photo;
    private Button btn_pick_photo;
    private Button btn_cancel;

    private static final int TAKE_PICTURE = 1;
    public static final int SELECT_PICTURE = 2;
    private static final int PERMISSION_CAMERA = 5;
    private static final int FINISH = 7;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_popupwindows);


        intent = getIntent();
        btn_take_photo = (Button) this.findViewById(R.id.item_popupwindows_camera);
        btn_pick_photo = (Button) this.findViewById(R.id.item_popupwindows_Photo);
        btn_cancel = (Button) this.findViewById(R.id.item_popupwindows_cancel);

        // 添加按钮监听
        btn_cancel.setOnClickListener(this);
        btn_pick_photo.setOnClickListener(this);
        btn_take_photo.setOnClickListener(this);

    }




    @Override
    public void onClick(View view) {
        switch (view.getId()) {
                case R.id.item_popupwindows_camera://拍照
                    try {
                        photo();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                 case R.id.item_popupwindows_Photo://相册选取
                     try {
                         //进入相册浏览界面;
                         Intent intent = new Intent(SelectPicPopupWindow.this, AlbumActivity.class);
                         intent.putExtra("fromActivity", "ApplyServiceOneActivity");
                         startActivityForResult(intent,SELECT_PICTURE);
                         overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);

                     } catch (Exception e) {

                     }
                     break;
                 case R.id.item_popupwindows_cancel://取消
                        finish();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
                case TAKE_PICTURE:
                    if (data != null) {
                        if (Bimp.getInstance().getTempSelectBitmap().size() < 5 && resultCode == RESULT_OK) {
                            //取得返回的Uri,基本上选择照片的时候返回的是以Uri形式，但是在拍照中有得机子呢Uri是空的，所以要特别注意
                            Uri mImageCaptureUri = data.getData();
                            //返回的Uri不为空时，那么图片信息数据都会在Uri中获得。如果为空，那么我们就进行下面的方式获取
                            if (mImageCaptureUri != null) {
                                Bitmap image;
                                try {
                                    //这个方法是根据Uri获取Bitmap图片的静态方法
                                    image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri);
                                    if (image != null) {
//                                    photo.setImageBitmap(image);
                                        String fileName = String.valueOf(System.currentTimeMillis());
                                        Bitmap bm = (Bitmap) data.getExtras().get("data");
                                        File tempDir = new File(FileUtil.getImgFile(this), "pinjia");
                                        if (!tempDir.exists()) {
                                            tempDir.mkdirs();
                                        }
                                        File tempPath = new File(tempDir, fileName + ".jpg");
                                        FileOutputStream out = new FileOutputStream(tempPath);
                                        bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                                        out.flush();
                                        out.close();
                                        ImageItem takePhoto = new ImageItem();
                                        takePhoto.setBitmap(bm);
                                        takePhoto.setImagePath(tempPath.getAbsolutePath());
                                        takePhoto.setSelected(true);
                                        Bimp.getInstance().getTempSelectBitmap().add(takePhoto);

                                        for (int i = 0; i < Bimp.getInstance().getTempSelectBitmap().size(); i++) {
                                            String imagePath = Bimp.getInstance().getTempSelectBitmap().get(i).getImagePath();
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                Bundle extras = data.getExtras();
                                if (extras != null) {
                                    //这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
                                    Bitmap image = extras.getParcelable("data");
                                    if (image != null) {
                                        try {
                                            String fileName = String.valueOf(System.currentTimeMillis());
                                            Bitmap bm = (Bitmap) data.getExtras().get("data");
                                            File tempDir = new File(FileUtil.getImgFile(this), "pinjia");
                                            if (!tempDir.exists()) {
                                                tempDir.mkdirs();
                                            }
                                            File tempPath = new File(tempDir, fileName + ".jpg");
                                            FileOutputStream out = new FileOutputStream(tempPath);
                                            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                                            out.flush();
                                            out.close();
                                            ImageItem takePhoto = new ImageItem();
                                            takePhoto.setBitmap(bm);
                                            takePhoto.setImagePath(tempPath.getAbsolutePath());
                                            takePhoto.setSelected(true);
                                            Bimp.getInstance().getTempSelectBitmap().add(takePhoto);

                                            for (int i = 0; i < Bimp.getInstance().getTempSelectBitmap().size(); i++) {
                                                String imagePath = Bimp.getInstance().getTempSelectBitmap().get(i).getImagePath();
                                            }
                                        } catch (Exception e) {
                                        }

                                    }
                                }
                            }

                        }

                    }
                    setResult(ApplyServiceOneActivity.GETPIC, intent);
                    finish();

                break;
            case SELECT_PICTURE :
                setResult(ApplyServiceOneActivity.GETPIC, intent);
                finish();
                break;

        }

    }


    /**
     * 进入照相的面;
     */
    public void photo() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请MOUNT_UNMOUNT_FILESYSTEMS权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CAMERA);
        } else {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, TAKE_PICTURE);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }


    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == PERMISSION_CAMERA) {
            if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, TAKE_PICTURE);
            } else {
                CUtils.showToast("请打开手机拍照权限后在操作");
            }
        }
    }





}
